<template>
    <el-dialog v-model="dialogTableVisible" :title="mode === 'add' ? t('新增') : t('修改')" :close-on-press-escape="false"
        :close-on-click-modal="false" :show-close="false" :draggable="true" @before-close="() => false" append-to-body
        style="width: 50%;">
        <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
            <div class="editor-container">
                <el-form ref="courseForm" :model="dataModel" label-width="auto" :rules="rules" style="width:100%">
                    <el-form-item :label="t('分类名称')" prop="name">
                        <el-input v-model="dataModel.name" />
                    </el-form-item>
                    <el-form-item :label="t('类型')" prop="type">
                        <el-select v-model="dataModel.type" :placeholder="t('请选择')" @change="handleChangeType">
                            <el-option v-for="item in typeOptions" :key="item.code" :label="item.label"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('父级分类')" prop="parentId">
                        <el-cascader v-model="dataModel.parentId" :placeholder="t('请选择')" :options="categoryOptions"
                            :props="{
                                checkStrictly: true
                            }" filterable />
                    </el-form-item>
                </el-form>
            </div>
        </FormBase>
    </el-dialog>
</template>
<script setup lang="ts">
import { Ref, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { t } from '@/common/locale';
import { FormRules } from 'element-plus';
import elHelper from '@/common/elHelper';
import { CategoryTypeOptions, getCategoryOptions, addCategory, updateCategory } from '@/api/category';
import comFunc from '@/common/comFunc';
import FormBase from '../layout/FormBase.vue';

const props = defineProps({
    data: {
        type: Object,
        default: {}
    },
    mode: {
        type: String,
        validator: (val: string) => {
            return ['add', 'modify'].includes(val)
        },
        default: 'add'
    },
    show: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['onSubmited', 'update:show'])

const dataModel: CategoryModel = reactive({
    name: '',
    objectId: '',
    parentId: '',
    type: ''
})
const typeOptions: Ref<{ code: string, label: string }[]> = ref(CategoryTypeOptions)
Object.assign(dataModel, props.data)
const mode = ref(props.mode)
const dialogTableVisible = ref(false)
const courseForm = ref()
const categoryOptions: Ref<CategorySelectOption[]> = ref([])
const rules = reactive<FormRules<CategoryModel>>({
    name: [
        { required: true, message: t('请输入分类名称'), trigger: 'blur' }
    ],
    type: [
        { required: true, message: t('请选择类型'), trigger: 'blur' }
    ]
})
watch(() => props.show, (val) => {
    dialogTableVisible.value = val
    if (val) {
        Object.assign(dataModel, props.data)
        mode.value = props.mode
        getOptions()
    }
})
const onSubmit = async () => {
    let valid = await courseForm.value.validate((valid) => valid)
    if (valid) {
        if (Array.isArray(dataModel.parentId)) {
            let arr = dataModel.parentId as string[]
            dataModel.parentId = arr[arr.length - 1]
        }
        if (mode.value === 'add') {
            const re = await addCategory(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        } else {
            const re = await updateCategory(dataModel)
            if (re.isSuccess) {
                emit('onSubmited', re.data!)
                elHelper.showSuccessMsg('操作成功')
                handleClose()
            } else {
                elHelper.showErrorMsg(re.msg)
            }
        }
    }
}
const handleClose = () => {
    dialogTableVisible.value = false
    emit('update:show', false)
}
const handleChangeType = (val) => {
    getOptions()
}
const getOptions = async () => {
    categoryOptions.value = await getCategoryOptions(comFunc.nvl(dataModel.type) as CategoryType)
}
onMounted(async () => {
    getOptions()
})
onUnmounted(() => {
    handleClose()
})
</script>
<style lang="scss" scoped>
.editor-container {
    width: 98%;
    display: flex;
    justify-content: center;
    justify-items: center;
}
</style>